package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiSnsGetuserinfoBycodeRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiSnsGetuserinfoBycodeResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.sms.SmsUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysDeptServiceImpl;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import com.ruoyi.zyx.domain.ZyxMemberDevice;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    private AjaxResult ajaxResult;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysDeptServiceImpl sysDeptService;

    @Autowired
    private ISysUserService sysUserService;


    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        if(SysUser.isAdmin(loginUser.getUser().getUserId())){
            ajax.put("isadmin", true);
        }else{
            ajax.put("isadmin", false);
        }
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 发送注册短信方法
     *
     * @param mobile
     * @return 结果
     */
    @PutMapping("/sendSmsReg/{mobile}")
    public AjaxResult sendSmsReg(@PathVariable("mobile") String mobile)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser sysUser=sysUserService.selectUserByUserName(mobile);
        if(null==sysUser||null==sysUser.getUserId()){
            ajax.put("isexist","0");
            try {
                int mobile_code = (int)((Math.random()*9+1)*1000);
                redisCache.setCacheObject(mobile, mobile_code, 60, TimeUnit.SECONDS);
                SmsUtils.sendSmsReg(mobile,String.valueOf(mobile_code));
                ajax = AjaxResult.success();
            } catch (Exception e) {
                ajax = AjaxResult.error();
                e.printStackTrace();
            }
        }else{
            ajax.put("isexist","1");
        }



        return ajax;
    }
    /**
     * 验证验证码是否正确
     *
     * @param sysUser
     * @return 结果
     */
    @GetMapping("/isRightSmsRegCode")
    public AjaxResult isRightSmsRegCode(SysUser sysUser)
    {
        AjaxResult ajax = AjaxResult.success();
        String sendcode= redisCache.getCacheObject(sysUser.getPhonenumber()).toString();
        if(null!=sendcode&&!sendcode.equals("")){
            if(Integer.valueOf(sendcode)==sysUser.getSmscode()){
//                ajax=AjaxResult.success("isright","1");
                ajax.put("isright","1");
            }else{
//                ajax=AjaxResult.success("isright","0");
                ajax.put("isright","0");
            }
        }else{
//            ajax=AjaxResult.success("isright","0");
            ajax.put("isright","0");
        }
        return ajax;
    }
    @PostMapping("/saveSign")
    public AjaxResult saveSign(@RequestBody SysUser sysUser)
    {
        AjaxResult ajax = AjaxResult.success();
        //新建机构
        SysDept sysDept=new SysDept();
        sysDept.setParentId(100L);//智医械
        sysDept.setDeptType("1");//企业/医院
        sysDept.setDeptName(sysUser.getDeptName());
        sysDept.setDeptType("1");
        sysDept.setStatus("0");
        sysDept.setPhone(sysUser.getPhonenumber());
        sysDept.setOrderNum("1");
        sysDeptService.insertRegDept(sysDept,sysUser);


        return  ajax;
    }

    @PostMapping("/sendBindCode")
    public AjaxResult sendBindCode(@RequestBody SysUser sysUser)
    {
        AjaxResult ajax = AjaxResult.success();
        try {
            int mobile_code = (int)((Math.random()*9+1)*1000);
            redisCache.setCacheObject("bind"+sysUser.getUserName(), mobile_code, 60, TimeUnit.SECONDS);
//            SmsUtils.sendSmsBind(sysUser.getUserName(),String.valueOf(mobile_code));
            ajax = AjaxResult.success();
        } catch (Exception e) {
            ajax = AjaxResult.error();
            e.printStackTrace();
        }
        return  ajax;
    }
    /**
     * 验证验证码是否正确
     *
     * @param sysUser
     * @return 结果
     */
    @GetMapping("/isRightSmsBindCode")
    public AjaxResult isRightSmsBindCode(SysUser sysUser)
    {
        AjaxResult ajax = AjaxResult.success();
        String sendcode= redisCache.getCacheObject("bind"+sysUser.getUserName()).toString();
        if(null!=sendcode&&!sendcode.equals("")){
            if(Integer.valueOf(sendcode)==sysUser.getSmscode()){
//                ajax=AjaxResult.success("isright","1");
                ajax.put("isright","1");
            }else{
//                ajax=AjaxResult.success("isright","0");
                ajax.put("isright","0");
            }
        }else{
//            ajax=AjaxResult.success("isright","0");
            ajax.put("isright","0");
        }
        return ajax;
    }
    //
    @PostMapping("/binduser")
    public AjaxResult binduser(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        String accesstoken=getddToken();
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
        OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
        req.setCode(loginBody.getCode());
        try {
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, accesstoken);
            String dduserid=rsp.getResult().getUserid();

            SysUser sysUser=sysUserService.selectUserByUserName(loginBody.getUsername());
            if(null==sysUser||null==sysUser.getUserId()){
                ajax.put("result",false);
            }else{
                sysUser.setDduserid(dduserid);
                sysUserService.updateUserDdUserid(sysUser);
                String token = loginService.login(sysUser.getUserName(), "");
                ajax.put(Constants.TOKEN, token);

                ajax.put("result",true);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }


        return ajax;
    }
    @PostMapping("/applogin")
    public AjaxResult applogin(@RequestBody LoginBody loginBody)
    {

        String accesstoken=getddToken();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("isbind","false");

        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo");
            OapiV2UserGetuserinfoRequest req = new OapiV2UserGetuserinfoRequest();
            req.setCode(loginBody.getCode());
            OapiV2UserGetuserinfoResponse rsp = client.execute(req, accesstoken);
            //根据ddopenid查看是否已经绑定 未绑定返回false 绑定生成token 返回 登录
            String dduserid=rsp.getResult().getUserid();
            if(null!=dduserid&&!dduserid.equals("")){
                SysUser sysUser=sysUserService.selectUserByDDuserId(rsp.getResult().getUserid());
                if(null==sysUser||null==sysUser.getUserId()){
                    ajax.put("isbind","false");
                }else{
                    ajax.put("isbind","true");
                    String token = loginService.login(sysUser.getUserName(), sysUser.getPassword());
                    ajax.put(Constants.TOKEN, token);
                }
            }


        } catch (Exception e) {
            System.out.println(e);
        }
        return ajax;
    }
    private String  getddToken(){
        String ret="";
        try {
            redisCache.deleteObject("ddtoken");
            ret=redisCache.getCacheObject("ddtoken");
            if(null==ret||ret.equals("")){
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
                OapiGettokenRequest req = new OapiGettokenRequest();
                req.setAppkey("dinghtlc3il5m43zjjt0");
                req.setAppsecret("X-ON9jcd6ukJBksSY7OPOY5HPukbShIlrtyODfEPu_OQKnAHz5UIHHSZZa4q50T2");
                req.setHttpMethod("GET");
                OapiGettokenResponse rsp = client.execute(req);
                ret=rsp.getAccessToken();
                redisCache.setCacheObject("ddtoken", rsp.getAccessToken(), 110, TimeUnit.MINUTES);
            }

        } catch (ApiException e) {
            e.printStackTrace();
        }
        return ret;
    }

}
